package taskservice;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import modelservice.Service;
import net.sf.json.JSONObject;
import utils.HttpHelper;

public class GeoDataServiceServer extends Service implements DataServer {
	
	private String userName;
	public GeoDataServiceServer(String ip, int port, String userName) {
		super(ip, port);
		this.userName = userName;
	}
	
	

	public String getUserName() {
		return userName;
	}



	public void setUserName(String userName) {
		this.userName = userName;
	}



	@Override
	public Data upload(String dataPath, String tag) throws Exception {
		//解析获取文件名和后缀
		File file = new File(dataPath);
		if(!file.exists()){
			return null;
		}
		String fileFullName = file.getName(); //包含文件名和后缀
		String fileName = fileFullName.substring(0,fileFullName.lastIndexOf("."));
		String ext = fileFullName.substring(fileFullName.lastIndexOf(".")+1, fileFullName.length());
		
		//post请求上传数据
		Map<String, String> fileMap = new HashMap<>();
		fileMap.put("file", dataPath);
		
		String actionURL = this.getBaseUrl() + "file/upload/store_dataResource_files";
		String result = HttpHelper.request_post_file(actionURL, fileMap, null);
		JSONObject jsResult = JSONObject.fromObject(result);
		if(jsResult.getInt("code") == 0){
			String dataId = jsResult.getString("data");
			//post请求，将上传的数据添加为数据资源
			String dataUrl = this.getBaseUrl() + "dataResource";
			JSONObject formData = new JSONObject();
			formData.put("author", this.getUserName());
			formData.put("fileName", fileName);
			formData.put("sourceStoreId", dataId);
			formData.put("suffix", ext);
			formData.put("type", "OTHER");
			
			String result2 = HttpHelper.request_post_json(dataUrl, formData);
			JSONObject jsResult2 = JSONObject.fromObject(result2);
			if(jsResult2.getInt("code") == 0){
				return new DCData(this.getIP(), this.getPort(), dataId);
			}else {
				return null;
			}
		}
		return null;
	}
	
	@Override
	public int connect(){
		String url = this.getBaseUrl();
		url = url + "ping";
		String body = HttpHelper.request_get(url, null);
		if(body == null){
			return 0;
		}else{
			JSONObject result = JSONObject.fromObject(body);
			// JSON Object
			if(result.getString("data").equals("OK")){
				return 1;
			}
			return 0;
		}
	}
	

}
